package com.example.demo.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.springframework.core.io.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.StringUtils;
import com.example.demo.constants.MultiMediaEntity;
import com.example.demo.constants.ResultEnity;
import com.example.demo.constants.pojo.UserInfo;
import com.example.demo.constants.pojo.UserRoleResultMap;
import com.example.demo.entity.MenuEntity;
import com.example.demo.entity.OperationLogEntity;
import com.example.demo.entity.UserEntity;
import com.example.demo.exception.BizException;
import com.example.demo.service.IMenuService;
import com.example.demo.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.log4j.Log4j2;

@Log4j2
@RestController
@RequestMapping("/base")
@Api(tags = "系统公共基础部分")
public class DemoBaseController extends BaseController {

	@Autowired
	IMenuService menuService;
	
	@Autowired
	IUserService userService;
	
	@Value("${demo-settings.ServerHost}")
	private String serverHost; 
	
	@RequestMapping({"/menu","~/demo/base/menu"})
	@ApiOperation( httpMethod = "POST", value = "获取菜单", notes = "获取菜单")
	public ResultEnity<List<Map<String,Object>>> menus(HttpServletRequest request, @ApiParam(name = "data", value = "查询条件",required = true) @RequestBody Map<String, Object> data){
		
		List<Map<String,Object>> result=null;
		String message="";
		
		try {	

			String jwt_token=request.getHeader("jwt_token");
			System.out.println(jwt_token);
			
			UserInfo userInfo=getCurrentUser(request);	
			System.out.println(userInfo);
			
			result = menuService.queryMenuList(data);
			message="操作成功";
		} 
		catch (BizException ex) {
			// TODO: handle exception
			return ResultEnity.Error(ex.getMessage(), null);
		}
		catch (Exception e) {
			// TODO: handle exception
		}		
		return ResultEnity.Success(message, result);
		
	}
	
	@RequestMapping("/menu/add")
	@ApiOperation( httpMethod = "POST", value = "添加菜单", notes = "添加菜单")
	public ResultEnity<String> addMenu(HttpServletRequest request, 
			@ApiParam(name = "data", value = "菜单对象",required = true) 
	   @RequestBody MenuEntity data){
		String result="";
		
		try {
			UserInfo userInfo=getCurrentUser(request);			
			data.setCreateBy(userInfo.getUserName());
			data.setCreateDate(new Date());			
			OperationLogEntity operationLog=new OperationLogEntity();
			operationLog.setOperatorUser(userInfo.getUserName());
			operationLog.setOperatorName(userInfo.getName());
			operationLog.setTitle("添加菜单");
			operationLog.setDescription(userInfo.getName()+"添加了 "+data.getName()+" 菜单");
			operationLog.setOperatType("01");			
			result = menuService.AddNewMenu(data, operationLog);
		}
		catch (BizException ex) {
			// TODO: handle exception
			return ResultEnity.Error(ex.getMessage(), ex);
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		
		return ResultEnity.Success("操作成功", result);
	}
	
	
	@RequestMapping("/user/list")
	@ApiOperation( httpMethod = "POST", value = "查询用户列表", notes = "查询用户列表")
	public ResultEnity<IPage<Map<String, Object>>> GetUserListForMap(@RequestBody Map<String,Object> params){
		
		IPage<Map<String, Object>> result=null;
		
		try {
			result = userService.QueryUserList(params);			 
		}
		catch (Exception ex) {
			// TODO: handle exception
			log.error("查询用户列表出错："+ex.getMessage(),ex);
			return ResultEnity.Error("查询用户列表出错", ex);
		}
		
		return ResultEnity.Success("查询成功", result);
		
	}
	
	@RequestMapping("/user/page")
	@ApiOperation( httpMethod = "POST", value = "查询用户列表", notes = "查询用户列表")
	public ResultEnity<IPage<UserEntity>> GetUserListForList(@RequestBody Map<String,Object> params){
		
		IPage<UserEntity> result=null;
		
		try {
			
			int size=(int)params.get("pageSize");
			int current=(int)params.get("currentPage");	
			
			QueryWrapper<UserEntity> wrapper=new QueryWrapper<>();
			
			String sex=(String)params.get("sex");
			if(!StringUtils.IsNullOrEmpty(sex)) {
				wrapper.eq("sex", sex);
			}
			
			result = userService.QueryUserList(current, size, wrapper);		 
		}
		catch (Exception ex) {
			// TODO: handle exception
			log.error("查询用户列表出错："+ex.getMessage(),ex);
			return ResultEnity.Error("查询用户列表出错", ex);
		}
		
		return ResultEnity.Success("查询成功", result);
		
	}
	
	
	@RequestMapping("/user/aop")
	@ApiOperation( httpMethod = "POST", value = "查询用户列表", notes = "查询用户列表")
	public ResultEnity<IPage<Map<String, Object>>> GetUserListForAOP(@RequestBody Map<String,Object> params){
		
		IPage<Map<String, Object>> result=null;
		
		try {

			int size=(int)params.get("pageSize");
			int current=(int)params.get("currentPage");	
		 
			Page<Map<String, Object>> pager=new Page<>(current,size);
			
			List<Map<String, Object>> records = userService.QueryUserList(pager,params);
			
			result=(IPage<Map<String, Object>>)pager;
			result.setRecords(records);
			
		}
		catch (Exception ex) {
			// TODO: handle exception
			log.error("查询用户列表出错："+ex.getMessage(),ex);
			return ResultEnity.Error("查询用户列表出错", ex);
		}
		
		return ResultEnity.Success("查询成功", result);
		
	}
	
	
	@RequestMapping("/user/list2")
	@ApiOperation( httpMethod = "POST", value = "查询用户列表", notes = "查询用户列表")
	public ResultEnity<IPage<UserRoleResultMap>> GetUserListForER(@RequestBody Map<String,Object> params){
		
		IPage<UserRoleResultMap> result=null;
		
		try {

			int size=(int)params.get("pageSize");
			int current=(int)params.get("currentPage");	
		 
			result= userService.QueryUserRoleList(params);
			
		}
		catch (Exception ex) {
			// TODO: handle exception
			log.error("查询用户列表出错："+ex.getMessage(),ex);
			return ResultEnity.Error("查询用户列表出错", ex);
		}
		
		return ResultEnity.Success("查询成功", result);
		
	}
	
	@RequestMapping("/user/list3")
	@ApiOperation( httpMethod = "POST", value = "查询用户列表返回Map", notes = "查询用户列表返回Map")
	public ResultEnity<IPage<Map<String, Object>>> GetUserListForEPMap(@RequestBody Map<String,Object> params){
		
		IPage<Map<String, Object>> result=null;
		
		try {

			result= userService.QueryUserRoleListMap(params);
			
		}
		catch (Exception ex) {
			// TODO: handle exception
			log.error("查询用户列表出错："+ex.getMessage(),ex);
			return ResultEnity.Error("查询用户列表出错", ex);
		}
		
		return ResultEnity.Success("查询成功", result);
		
	}
	
	
	@RequestMapping("/media/upload")
	@ApiOperation( httpMethod = "POST", value = "上传文件", notes = "上传文件")
	public ResultEnity<MultiMediaEntity> UploadMultiMedia(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("file") MultipartFile file) throws IOException{
		
		MultiMediaEntity result=null;	
		
		if (file.isEmpty()) {
            return ResultEnity.Error("上传失败，请选择文件", null);
        }
		
	    try {
	    	
	    	UserInfo currentUser=getCurrentUser(request);	
	    	if(currentUser==null) {
	    		return ResultEnity.Error("没有获取到登陆人信息，请重新登陆再试一下", null);
	    	}
	    	
	    	String fileName = file.getOriginalFilename();
	  	    String filePath = ResourceUtils.getURL("classpath:").getPath();
	  	    filePath=filePath.replace("/target/classes/", "/springupload/");
	  	    filePath=java.net.URLDecoder.decode(filePath, "utf-8");
	  	    
	  	    //检查有无该文件夹没有则创建
	  	    File targetFile=new File(filePath);
	  	    if(!targetFile.exists()) {
	  	    	targetFile.mkdirs();
	  	    }
	  	    
	  	    String fileFormat=fileName.substring(fileName.lastIndexOf('.'));
	  	    
	  	    int materialType=0;
	  	    switch(fileFormat.toLowerCase()) {
	  	        case ".txt":
	  	        case ".word":
	  	        case ".doc":
	  	        case ".docx":
	  	        case ".xls":
	  	        case ".xlsx":
	  	        	materialType=0;
	  	        break;
	  	        case ".jpg":
	  	        case ".png":
	  	        case ".gif":
	  	        case ".bmp":
	  	        	materialType=1;
	  	        break;
	  	        case ".7z":
	  	        case ".rar":
	  	        case ".zip":
	  	        	materialType=2; 
	  	    	break;
	  	        default:
	  	        	materialType=-1;
	  	        break;
	  	    }
	  	    
	  	    result=new MultiMediaEntity();
	  	    result.setMaterialName(fileName);
	  	    result.setMaterialType(materialType);
	  	    result.setMediaFormat(fileFormat);
	  	    
//	  	    SimpleDateFormat dataFormat=new  SimpleDateFormat("yyyyMMddHHmmss");
//	  	    fileName="m"+dataFormat.format(new Date()).toString()+fileFormat;
	  	    
	  	    fileName=StringUtils.GetNonce().toString()+fileFormat;
	  	    
	  	    File destFile = new File(filePath + fileName);
	  	    file.transferTo(destFile);
	  	    
	  	    log.info(currentUser.getUserName()+"上传了"+fileName+"文件");
	  	    
	  	    String tempServerHost=serverHost;
	  	    if(!StringUtils.IsNullOrEmpty(serverHost))
	  	    	tempServerHost=StringUtils.TrimEnd(tempServerHost, '/');
	  	    result.setResourceUrl(tempServerHost+"/base/media/download/"+fileName);
	  	    
	  	    log.info("上传文件成功"+result);
	  	    
	    }
	    catch (BizException ex) {
			// TODO: handle exception
	    	response.sendError(401,"没有权限");
	    	log.error("上传文件出错:"+ex.getMessage(),ex);
	    	return ResultEnity.Error("上传文件出错:"+ex.getMessage(), ex);
		}
	    catch (Exception ex) {
			// TODO: handle exception
	    	log.error("上传文件出错:"+ex.getMessage(),ex);
	    	return ResultEnity.Error("上传文件出错:"+ex.getMessage(), ex);
		}
		
		return ResultEnity.Success("上传成功", result);	
		
	}
	
	
	@ApiOperation(httpMethod = "GET", value = "下载文件", notes = "下载文件")
	@RequestMapping(value = "/media/download/{file}",method = RequestMethod.GET)
	public ResponseEntity<Resource> DownloadResources(HttpServletRequest req,
			@PathVariable String file) throws FileNotFoundException, UnsupportedEncodingException{
		
		String message="";
		MultiMediaEntity data=null;
		
		if(!StringUtils.IsNullOrEmpty(file)) {		
			file=file.toLowerCase();
		}
		
	    String filePath = ResourceUtils.getURL("classpath:").getPath();
	    filePath=filePath.replace("/target/classes/", "/springupload/");
	    filePath=java.net.URLDecoder.decode(filePath, "utf-8");

        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); 
//        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+file+"");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        ByteArrayResource resourceByteArray=null;
        File fileResource=new File(filePath+file);
        MediaType mediaType=MediaType.parseMediaType("application/octet-stream");
        
	    try {  
	    	
	  	    if(fileResource.exists()) {	  	    	
	  	        Path path = Paths.get(fileResource.getAbsolutePath());
	  	        resourceByteArray = new ByteArrayResource(Files.readAllBytes(path));		  	    
	  	    } 
	  	    
	  	    boolean imageFormat=false;
	  	    
	  	    if(file.endsWith(".png")) {
	  	    	mediaType=MediaType.IMAGE_PNG;
	  	    	imageFormat=true;
	  	    }
	  	    else if(file.endsWith(".jpg")){
	  	    	mediaType=MediaType.IMAGE_JPEG;
	  	    	imageFormat=true;
			}
	  	    else if(file.endsWith(".gif")){
	  	    	mediaType=MediaType.IMAGE_GIF;
	  	    	imageFormat=true;
			}
	  	    
	  	    if(!imageFormat) {
	  	    	 headers.add("Content-disposition", "attachment; filename=" + file);
	  	    }
			
		} 
	    catch (Exception e) {
			// TODO: handle exception
	    	log.info("下载文件出错:"+e.getMessage(),e);
		}	  
		
	    return ResponseEntity.ok()
	            .headers(headers)
	            .contentLength(fileResource.length()) 
	            .contentType(mediaType)
	            .body(resourceByteArray);
	    
	}
	
}
